package fsmi.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fsmi.dao.StudentDB;
import fsmi.daoservice.StudentDAO;

/**
 * Servlet implementation class Login
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String userID = request.getParameter("userID");
		// get password
		String password = request.getParameter("password");
		// check weather user exists and weather password is right
		StudentDAO studentDB = new StudentDB();
		boolean userExists = studentDB.checkStuExsits(userID);
		boolean passwordOk = studentDB.checkStuPassword(userID, password);
		// if all above is ok,set session:userID and jump to course ui
		HttpSession session = request.getSession();
		session.setAttribute("userID", userID);
		response.setContentType("text/html;charset=utf-8");
		RequestDispatcher dispatcher = null;
		if (!userExists) {
			dispatcher = request.getRequestDispatcher("/view/userNotFound.html");
			dispatcher.forward(request, response);
		} else if (!passwordOk) {
			dispatcher = request.getRequestDispatcher("/view/passwordErorr.html");
			dispatcher.forward(request, response);
		} else {
			dispatcher = request.getRequestDispatcher("/Course");
			dispatcher.forward(request, response);
		}
	}

}
